package com.gyy.socket;


import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SocketServer extends Thread {

    public Map<String, Socket> clientMap = new HashMap<>();

    public void run() {
        try {
            //创建socket服务端
            @SuppressWarnings("resource")
            ServerSocket server = new ServerSocket(9666);
            while (true) {
                System.out.println("建立监听");
                Socket client = server.accept();
                System.out.println("建立连接");
                //获取注册包
                InputStream is = client.getInputStream();
                byte[] bytes = ModBusUtils.readInputStream(is);
                String str = "";
                for (int i = 0; i < bytes.length; i++) {
                    if (i == 0) {
                        System.out.print("十进制：" + bytes[i] + " ");
                    } else {
                        System.out.print(bytes[i] + " ");
                    }
                    str = str + ModBusUtils.byteToASCLL(bytes[i]);
                }
                System.out.println("十六进制：" + ModBusUtils.bytes2HexString(bytes));
                System.out.println("注册包：" + str);
                //添加客户端
                clientMap.put(str, client);
                Service service = new Service(clientMap);
                service.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

